<template>
  <div class="c-textAlign-l">
    <open-modal class="c-pz10000" :openModal='isOpenSharePopup' @closeModal='closeSharePopup'>
      <div class="c-bg-white c-br-tl20 c-br-tr20 c-text-hidden c-pb40">
        <div class="c-pb30 c-p">
          <div class="c-w100 c-textAlign-c c-fs28 c-pt24 c-fc-xblack">赠送方式</div>
          <span @click="closeSharePopup" class="iconfont c-pa c-p-t24 c-p-r24 c-fc-sgray c-fs30 c-ww32 c-hh32 c-brp50 c-flex-row c-flex-center">&#xe6e1;</span>
        </div>
        <div class="c-maxh600 c-contexty-scroll c-ph24">
          <div class="c-fs22 c-fc-gray c-lh32">
            转赠好友后，赠送人不能再使用该{{(item ? item.type : 2) | filterType}}；可同时转赠多人，优先领取者获得该券，其余人不能再次领取。
          </div>
          <div class="c-flex-row c-justify-sb c-mt40 c-ph30">
            <div class="c-flex-column c-aligni-center c-flew-1" @click="clickShare(1)">
              <img class="c-ww80 c-hh80" :src="require('@/assets/i/wap/coupon/weixin.png')" alt="">
              <div class="c-mt16 c-fs24 c-fc-sblack">微信好友</div>
            </div>
            <div class="c-flex-column c-aligni-center c-flew-1" @click="clickShare(2)">
              <img class="c-ww80 c-hh80" :src="require('@/assets/i/wap/coupon/code.png')" alt="">
              <div class="c-mt16 c-fs24 c-fc-sblack">二维码</div>
            </div>
            <div class="c-flex-column c-aligni-center c-flew-1" @click="clickShare(3)">
              <img class="c-ww80 c-hh80" :src="require('@/assets/i/wap/coupon/copy.png')" alt="">
              <div class="c-mt16 c-fs24 c-fc-sblack">复制链接</div>
            </div>
          </div>
        </div>
      </div>
    </open-modal>
    <div v-show="isShowCode" class="c-pz10000">
      <div class="c-translucent-balck50 c-pf c-p-t0 c-p-b0 c-p-l0 c-p-r0 c-pz10000" @click="isShowCode = false;goGiftTransfer();"></div>
      <div class="c-pf c-p-t0 c-p-b0 c-p-l0 c-p-r0 c-ww600 c-table margin-auto c-pz10000">
        <img src="" class="c-w100" id="shareExImg" />
      </div>
    </div>
    <div v-if="item" class="ww640px canvasBox c-bg-transparent" id="exCanvas">
      <div class="c-p c-pz10 ww640px hh750px c-textAlign-l c-bg-transparent">
        <img class="c-pa c-pz-1 ww640px hh750px pt20px" :src="require('@/assets/i/wap/coupon/bg1.png')" alt="">
        <div class="c-flex-row c-aligni-center c-justify-sb headImg">
          <img class="c-brp50 c-flex-shrink0" :src="$addXossFilter(userHeadImg, require('@/assets/defult_head.png'))" alt="">
          <span class="ml20px c-flex-grow1 c-w0 fs28px c-fc-sblack c-text-ellipsis1">{{userName}}</span>
        </div>
        <div class="c-flex-column c-aligni-center">
          <div class="c-p ww480px hh160px mt60px">
            <img class="c-pa c-pz-1 ww480px hh160px" :src="require('@/assets/i/wap/coupon/coupon-bg.png')" alt="">
            <div class="c-flex-row c-justify-sb">
              <div class="ww130px hh160px fs20px c-flex-shrink0 c-flex-column c-flex-center c-fc-white c-textAlign-c">
                <template v-if="item.type != 4 && item.type != 1">
                  <div v-if="item.type == 5" class="c-fw-b fs52px">{{Number(item.price)}}<span class="fs20px">折</span></div>
                  <div v-else class="c-fw-b ww130px"><span :class="item.price.length > 5 ? '20px' : 'fs28px'">{{'¥' | iosPriceFilter}}</span><span class="c-lh" :class="item.price.length > 5 ? 'fs24px' : item.price.length > 3 ? 'fs40px' : 'fs52px'">{{Number(item.price)}}</span></div>
                  <!-- <div v-if="couponType == 4">{{item.type == 6 ? '付费券' : '免费券'}}</div> -->
                  <div>{{Number(item.amount) > 0 ? '满'+Number(item.amount)+'可用' : '无门槛'}}</div>
                </template>
                <div class="fs34px" v-else>{{item.type == 4 ? '抵价券' : '兑换券'}}</div>
              </div>
              <div class="c-flex-grow1 c-w100 hh160px ph24px c-flex-column c-justify-sb pv16px c-textAlign-l">
                <div class="ww320px c-fc-xblack fs28px c-fw600 c-text-ellipsis1">
                  {{formatLength(item.name, 12)}}
                </div>
                <div class="fs20px c-fc-gray mt10px" v-if="item.type != 1">{{item.redeemType == 26 ? '全店商品可用' : item.redeemType == 25 ? '适用于商城商品' : item.redeemType == 114 ? '适用于预约师资功能' : item.redeemType == 27 ? (("适用于" + (item.prodTypes ? item.prodTypes.join('、') : '')).length > 15 ? (("适用于" + (item.prodTypes ? item.prodTypes.join('、') : '')).substring(0, 14) + '...') : ("适用于" + (item.prodTypes ? item.prodTypes.join('、') : ''))) : '指定商品可用'}}</div>
                <div class="fs20px c-fc-gray mt10px  c-wb-ba">
                  <div v-if="item.validStatus != 1 && item.validStatus != 2 && item.startAt && item.endAt">
                    {{item.startAt}} - {{formatLength(item.endAt, 11)}}
                  </div>
                  <div v-else>
                    {{item.validStatus == 1 ? ('领券当日起' + item.validPeriod + '天内可用') : ('领券次日起' + item.validPeriod + '天内可用')}}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="mt100px c-flex-column c-flex-center">
          <img class="qrCode" :src="qrCode" alt="">
          <div class="c-fc-white fs24px c-mt20">长按扫码，领取{{(item ? item.type : 2) | filterType}}</div>
        </div>
      </div>
    </div>
    <share-masker :isShowShare="isShowShareMask" v-if="isShowShareMask" @closeShare="isShowShareMask=false;goGiftTransfer();"></share-masker>
  </div>
</template>

<script>
import OpenModal from "@/components/templates/common/openModal.vue";
import shareMasker from "@/components/templates/common/shareMasker.vue";
import { utilJs } from "@/utils/common.js";
let html2canvas = null;
export default {
  name: 'ShareCom',
  components: {
    OpenModal,
    shareMasker,
  },
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    item: {
      type: Object,
      default: () => {}
    }
  },
  filters: {
    filterType(val) {
      switch (val) {
        case 1:
          return '兑换券'
        case 2:
          return '无门槛券'
        case 3:
          return '满减券'
        case 4:
          return '抵价券'
        case 5:
          return '折扣券'
      }
    }
  },
  watch: {
    isShow(val) {
      this.isOpenSharePopup = val;
      if (val) {
        this.getGiftCouponQrCode();
      }
    }
  },
  data() {
    return {
      isOpenSharePopup: false,
      isShowShareMask: false, // 是否展示分享蒙层提示
      isShowCode: false, // 是否展示二维码
      userHeadImg: '', // 用户头像
      userName: '', // 用户名称
      qrCode: '',
    }
  },
  created() {
  },
  mounted() {
    this.userHeadImg = localStorage.getItem("userHeadImg") || '';
    this.userName = localStorage.getItem("userName");
    this.isOpenSharePopup = false;
    this.isShowShareMask = false;
    this.isShowCode = false;
    this.qrCode = '';
  },
  methods: {
    formatLength(val, len) {
      return val.length <= len ? val : val.substring(0, len - 2) + '...';
    },
    drawShareImg() {
      import(/* webpackChunkName: "html2canvas" */"@/utils/html2canvas.js").then(res => {
        html2canvas = res.default;
        this.startCanvas();
      })
    },
    startCanvas() {
      let domTest = document.getElementById("exCanvas");
      if (!domTest) {
        return;
      }
      this.$loading.show({
        text: "分享图片生成中"
      });
      html2canvas(domTest, { useCORS: true, backgroundColor: 'rgba(0, 0, 0, 0)' }).then(canvas => {
        let ctx = canvas.getContext("2d");
        this.canvasToImage(ctx);
      });
    },
    canvasToImage(ctx) {
      try {
        let dataURL = ctx.canvas.toDataURL("image/png?x-oss-process=style/common");
        document.getElementById("shareExImg") && document.getElementById("shareExImg").setAttribute("src", dataURL);
        this.isShowCode = true;
        this.$loading.hide();
      } catch (err) {
        this.$loading.hide();
        console.log(err.message);
        console.log(err.stack);
      }
    },
    openSharePopup() {
      this.isOpenSharePopup = true;
    },
    closeSharePopup() {
      this.isOpenSharePopup = false;
      this.$emit('closeSharePopup')
    },
    // 触发转赠状态
    changeGiftCouponStatus(status) { // status 1转赠操作 -1 取消转赠
      let data = {
        status: status,
        eRcdId: this.item.eRcdId
      }
      utilJs.postMethod(`${global.apiurl}coupon/giftCoupon`, data, res => {
        // 切换转赠状态，优惠券列表也要切到转赠中
        this.$emit('changeStatus', 2)
      })
    },
    clickShare(type) {
      this.closeSharePopup();
      if (type == 1) {
        this.isShowShareMask = true;
        this.changeWechatShare();
      } else if (type == 2) {
        this.drawShareImg();
      } else {
        this.copyCodeText()
      }
      this.changeGiftCouponStatus(1)
    },
    goGiftTransfer() {
      if (!this.item) {
        return;
      }
      this.$routerGo(this, "push", {
        path: "/member/myValueVoucher/giftTransfer",
        query: {
          eRcdId: this.item.eRcdId,
          redeemCodeId: this.item.redeemCodeId
        }
      });
    },
    changeWechatShare() {
      if (!this.item) {
        return;
      }
      let title = this.item.name || '优惠券';
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareUrl =
        window.location.href.split("#")[0] +
        `#/homePage/giftCode/${this.item.redeemCodeId}?refereeId=` +
        localStorage.getItem("userId") + '&isScan=1&type=1&isGift=1&eRcdId=' + this.item.eRcdId;
      let shareDesc = window.localStorage.getItem("shareDesc");
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc);
    },
    async copyCodeText() {
      let shareUrl =
        window.location.href.split("#")[0] +
        `#/homePage/giftCode/${this.item.redeemCodeId}?refereeId=` +
        localStorage.getItem("userId") + '&isScan=1&type=1&isGift=1&eRcdId=' + this.item.eRcdId;
        await utilJs.copyText(shareUrl);
        this.goGiftTransfer();
    },
    getGiftCouponQrCode() {
      let postUrl = `${global.apiurl}coupon/giftCouponQrCode?redeemCodeId=${this.item.redeemCodeId}&eRcdId=${this.item.eRcdId}`;
      utilJs.getMethod(postUrl, res => {
        this.qrCode = res.QrLogo;
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.canvasBox {
  top: -999px;
  left: -1000px;
  z-index: -999;
  position: absolute;
  /* background: rgba(155, 0, 0, 0); */
  /* background-color: #fff; */
}
.headImg {
  padding-top: 60px;
  padding-left: 80px;
  padding-right: 80px;
}
.headImg img {
  width: 80px;
  height: 80px;
}
.qrCode {
  width: 180px;
  height: 180px;
}
.ww130px {
  width: 130px;
}
.ww320px {
  width: 320px;
}
.ww480px {
  width: 480px;
}
.ww640px {
  width: 640px;
}
.hh160px {
  height: 160px;
}
.hh750px {
  height: 750px;
}
.ml20px {
  margin-left: 20px;
}
.margin-auto {
  margin: auto;
}
.mt10px {
  margin-top: 10px;
}
.mt60px {
  margin-top: 60px;
}
.mt100px {
  margin-top: 100px;
}
.pt20px {
  padding-top: 20px;
}
.pv16px {
  padding-top: 16px;
  padding-bottom: 16px;
}
.ph24px {
  padding-left: 24px;
  padding-right: 24px;
}
.fs20px {
  font-size: 20px;
}
.fs24px {
  font-size: 24px;
}
.fs28px {
  font-size: 28px;
}
.fs34px {
  font-size: 34px;
}
.fs40px {
  font-size: 40px;
}
.fs52px {
  font-size: 52px;
}

</style>
